package yun.web.activerecord.dialect.pg;

import yun.web.activerecord.Config;
import yun.web.activerecord.Record;
import yun.web.activerecord.RecordBuilder;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static yun.web.activerecord.dialect.pg.type.PG.castType;

/*------------------------
      author: 张天笑
      date: 2019/3/12
      time: 0:12
   规定 rs 对象如何封装成Record
-------------------------*/
public class PGRecordBuilder extends RecordBuilder {
    @Override
    public List<Record> build(Config config, ResultSet rs) throws SQLException {
        List<Record> result = new ArrayList<Record>();
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        String[] labelNames = new String[columnCount + 1];
        int[] types = new int[columnCount + 1];
        buildLabelNamesAndTypes(rsmd, labelNames, types);

        while (rs.next()) {
            Record ar = new Record();
            Map<String, Object> attrs = ar.getColumns();
            buildMap(attrs, rs, labelNames, columnCount);
            result.add(ar);
        }

        return result;
    }

    public static void buildMap(Map<String, Object> attrs, ResultSet rs
            , String[] labelNames
            , int columnCount) throws SQLException {
        for (int i = 1; i <= columnCount; i++) {
            String column_name = labelNames[i];
            attrs.put(column_name, castType(rs.getObject(i)));
        }
    }


}
